package com.itxialu.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itxialu.reggie.common.BaseContext;
import com.itxialu.reggie.common.CustomException;
import com.itxialu.reggie.entity.*;
import com.itxialu.reggie.mapper.OrdersMapper;
import com.itxialu.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 订单
 *
 * @author shkstart
 * @create 2022-11-07 23:14
 */
@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    //订单接口
    @Autowired
    private OrdersService ordersService;

    //订单明细表接口
    @Autowired
    private OrderDetailService orderDetailService;

    //购物车接口
    private ShoppingCartService shoppingCartService;

    //用户接口
    private UserService userService;

    //地址接口
    private AddressBookService addressBookService;

    //用户下单
    @Override
    public void submit(Orders orders) {
        //1.获取当前用户
        long userId = BaseContext.getCurrentId();
        //2.查询当前购物车的数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> ShoppingCart = shoppingCartService.list(wrapper);//购物车数据
        if (ShoppingCart == null || ShoppingCart.size() == 0) {
            throw new CustomException("购物车为空,不能下单！");
        }

        //查用户数据
        User user = userService.getById(userId);
        //查地址数据
        Long addressBookId = orders.getAddressBookId();//地址簿ID
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            throw new CustomException("地址簿为空,不能下单！");
        }

        //3.遍历购物车生成订单明细表，并算出金额
        AtomicInteger amount = new AtomicInteger(0);//原子操作类，保证线程安全
        long id = IdWorker.getId();//订单号

        List<OrderDetail> orderDetails = ShoppingCart.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();//订单明细实体类
            orderDetail.setOrderId(id);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //4.向订单表插入数据：一条数据
        //添加订单号，mybatisplus提供的订单号功能
        orders.setId(id);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(id));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据，一条数据
        ordersService.save(orders);
        //5.向订单明细表插入数据：可能多条（从购物车里拿订单明细）
        orderDetailService.saveBatch(orderDetails);//逐条插入
        //6.清空购物车数据
        shoppingCartService.remove(wrapper);
    }
}
